// Application/Services/MenuTreeBuilder.cs
namespace UniversalAdmin.Application.Services;

public class MenuTreeBuilder
{
  private readonly Domain.Repositories.IMenuRepository _menuRepository;

  public MenuTreeBuilder(Domain.Repositories.IMenuRepository menuRepository)
  {
    _menuRepository = menuRepository;
  }

  public async Task<List<DTOs.MenuTreeDto>> BuildMenuTreeAsync()
  {
    var flatMenus = await _menuRepository.GetMenusFlatAsync();
    return BuildTree(flatMenus);
  }

  private static List<DTOs.MenuTreeDto> BuildTree(
      IEnumerable<Domain.Entities.Menu> menus,
      int? parentId = null)
  {
    return menus
        .Where(m => m.ParentId == parentId)
        .OrderBy(m => m.Sort)
        .Select(menu => new DTOs.MenuTreeDto
        {
          Id = menu.Id,
          Name = menu.Name,
          Path = menu.Path,
          Icon = menu.Icon,
          ParentId = menu.ParentId,
          Sort = menu.Sort,
          IsActive = menu.IsActive,
          Children = BuildTree(menus, menu.Id)
        }).ToList();
  }
}